﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using Wicresoft.Common;
using JDEduTrain.Framework.Business;
using JDEduTrain.Framework.ViewEntity;
using JDEduTrain.Framework.Entity;
using Wicresoft.Framework.Organization;
using NameControlLib;

public partial class Page_TrainDetailStat : BaseAuthenticationPage
{

    public string SearchDefaultText
    {
        get
        {
            return "搜索 学员名称";
        }
    }

    public string SearchClause
    {
        get
        {
            if (ViewState["SearchClause"] == null)
                ViewState["SearchClause"] = "1=1";
            return ViewState["SearchClause"].ToString();
        }
        set
        {
            ViewState["SearchClause"] = value;
        }
    }
    protected DataTable DTUserPageList
    {
        get
        {
            if (ViewState["DTUserPageList"] != null)
            {
                return (DataTable)ViewState["DTUserPageList"];
            }
            return new DataTable();
        }
        set
        {
            ViewState["DTUserPageList"] = value;
        }
    }


    protected void Page_Load(object sender, EventArgs e)
    {
        this.tbSearch.Attributes.Add("onfocus", string.Format("clearText(this, '{0}');", SearchDefaultText));
        this.tbSearch.Attributes.Add("onblur", string.Format("insertText(this, '{0}');", SearchDefaultText));
        this.tbSearch.Attributes.Add("onkeydown", "searchClick();");
        this.ShowLRLayoutButton = false;
        this.ShowUDLayoutButton = false;
        this.ShowSimpleLayoutButton = false;
        this.ShowAdvancedSearch = false;

        this.Title = "学员列表";
        if (!IsPostBack)
        {
            tbSearch.Text = SearchDefaultText;
            this.Order.OrderColumn =  UserExtend.SQLCOL_THIRDLEVELDEPTDISPLAYNAME;
            this.Order.OrderDirection = "DESC";
            BindData();
        }

    }

    protected override void Pager_PageChanged(object sender, EventArgs e)
    {
        BindData();
        base.Pager_PageChanged(sender, e);
    }

    protected override void Order_OrderChanged(object sender, EventArgs e)
    {
        BindData();
        base.Order_OrderChanged(sender, e);
    }

    private void BindData()
    {
        int recordCount = 0;
        DataTable dtUser = BLTrain.GetUserList(0,int.MaxValue, SearchClause, string.Format("{0} {1}", this.Order.OrderColumn, this.Order.OrderDirection), ref recordCount);
        DTUserPageList = dtUser.Clone();
        DTUserPageList.Clear();
        recordCount = 0;
        if (OrganizationHelper.IsUserInRole(CurrentUser.ID, AppConfig.MinistryAdminRoleID))
        {
            foreach (DataRow dr in dtUser.Rows)
            {
                //按人事所在三级实体管理
                Department currMainDept = OrganizationHelper.GetDepartmentInfo(CurrentUser.MainDepartmentID);
                string deptPath = currMainDept.IDPath;
                string[] deptIDs = deptPath.Split('/');
                string mainDeptID = string.Empty;
                if (deptIDs.Length >= 4)
                {
                    mainDeptID = deptIDs[3];
                }
                else
                {
                    mainDeptID = CurrentUser.MainDepartmentID.ToString();
                }


                UserExtend userExtend = new UserExtend(new Guid(dr["ID"].ToString()));
                if (userExtend.Load())
                {
                    //取三级实体部门
                    Department dept = OrganizationHelper.GetDepartmentInfo(userExtend.MainDepartmentID);
                    if (dept != null)
                    {
                        string[] userDeptIDs = dept.IDPath.Split('/');
                        if (userDeptIDs.Length >= 4)
                        {
                            dr["ThirdLevelDeptDisplayName"] = OrganizationHelper.GetDepartmentInfo(new Guid(userDeptIDs[3])).DisplayName;
                        }
                    }
                }
                if (!string.IsNullOrEmpty(mainDeptID))
                {
                    if (OrganizationHelper.IsUserInDepartment(new Guid(dr["ID"].ToString()), new Guid(mainDeptID)))
                    {
                        DTUserPageList.ImportRow(dr);
                        recordCount++;
                    }
                }
            }
            DTUserPageList = WebCommon.GetPagedTable(DTUserPageList, Pager.PageIndex + 1, Pager.PageSize);

        }
        else if (OrganizationHelper.IsUserInRole(CurrentUser.ID, AppConfig.OrganizeAdminRoleID))
        {
            DTUserPageList = BLTrain.GetUserList(Pager.PageIndex, Pager.PageSize, SearchClause, string.Format("{0} {1}", this.Order.OrderColumn, this.Order.OrderDirection), ref recordCount);
        }
        Pager.RecordCount = recordCount;
        DTUserPageList.Columns.Add("YearScore");
        DTUserPageList.Columns.Add("TotalScore");
        DTUserPageList.Columns.Add("DeptDisplayName");
        foreach (DataRow dr in DTUserPageList.Rows)
        {
            dr["YearScore"] = BLTrain.GetYearScoreByMemberID(new Guid(dr["ID"].ToString()));
            dr["TotalScore"] = BLTrain.GetAllScoreByMemberID(new Guid(dr["ID"].ToString()));
            UserExtend userExtend = new UserExtend(new Guid(dr["ID"].ToString()));
        }
	DataView dvUser = DTUserPageList.DefaultView;
	dvUser.Sort = "YearScore" + " desc";
        rptUserInfo.DataSource = dvUser;
        rptUserInfo.DataBind();

    }

    protected void ddlCategory_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindData();
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        if (tbSearch.Text != string.Empty && tbSearch.Text != SearchDefaultText)
            SearchClause = string.Format("{0} LIKE N'%{1}%'", UserExtend.SQLCOL_FULLNAME, tbSearch.Text);
        else
            SearchClause = "1=1";
        BindData();
    }
    protected void btnAdvancedSearch_Click(object sender, EventArgs e)
    {
        BindData();

    }
    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        BindData();
    }

    protected void lbtnPrint_Click(object sender, EventArgs e)
    {
        this.OutExcel("attachment;filename=" + HttpUtility.UrlEncode("学习情况汇总表(" + DateTime.Now.ToString("yyyy-MM-dd") + ")") + ".xls", "application/ms-excel");
    }

    private void OutExcel(string name, string type)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "GB2312";
        Response.AppendHeader("Content-Disposition", name);
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        Response.ContentType = type;

        string tableBegin = @"
                    <html xmlns:x='urn:schemas-microsoft-com:office:excel'>
                    <head>
                    </head>
                    <body>
                <table class='Table' cellspacing='1' cellpadding='3' rules='all' border='1' id='dgTask' style='width:98%;'>
						<tr style='font-weight:bold; color: #000000; text-align: center; font-size: 30; border:0'>
							<td colspan='13'>{0}</td>
						</tr>
						<tr style='font-weight:bold; color: #000000; text-align: center;  font-size: 13;'>
							<td style='width:120px;background-color: #dfdfdf; border:.5pt solid black'>单位</td>							
							<td style='width:120px;background-color: #dfdfdf; border:.5pt solid black'>姓名</td>
                            <td style='width:50px;background-color: #dfdfdf; border:.5pt solid black'>性别</td>
							<td style='width:75px;background-color: #dfdfdf; border:.5pt solid black'>出生年月</td>
							<td style='width:100px;background-color: #dfdfdf; border:.5pt solid black'>职级</td>
                            <td style='width:100px;background-color: #dfdfdf; border:.5pt solid black'>职务</td>
                            <td style='width:200px;background-color: #dfdfdf; border:.5pt solid black'>班级名称</td>
                            <td style='width:120px;background-color: #dfdfdf; border:.5pt solid black'>主办单位</td>
                            <td style='width:100px;background-color: #dfdfdf; border:.5pt solid black'>培训层级</td>
                            <td style='width:75px;background-color: #dfdfdf; border:.5pt solid black'>培训天数</td>
                            <td style='width:160px;background-color: #dfdfdf; border:.5pt solid black'>培训时间</td>
                            <td style='width:75px;background-color: #dfdfdf; border:.5pt solid black'>学分</td>
                            <td style='width:75px;background-color: #dfdfdf; border:.5pt solid black'>培训年份</td>
						</tr>";
        string tableEnd = @"</table></body></html>";
        string tableBody = "";

        string tableBodyTemplate = @"<tr align='Left' style='font-size: 13;'>
				<td style='border:.5pt solid black;'>{0}</td>
				<td style='border:.5pt solid black;'>{1}</td>
				<td style='border:.5pt solid black;'>{2}</td>
				<td style='border:.5pt solid black;'>{3}</td>
				<td style='border:.5pt solid black;'>{4}</td>
				<td style='border:.5pt solid black;'>{5}</td>
				<td style='border:.5pt solid black;'>{6}</td>
				<td style='border:.5pt solid black;'>{7}</td>
				<td style='border:.5pt solid black;'>{8}</td>
				<td style='border:.5pt solid black;'>{9}</td>
				<td style='border:.5pt solid black;'>{10}</td>
				<td style='border:.5pt solid black;'>{11}</td>
				<td style='border:.5pt solid black;'>{12}</td>
				</tr>";
        string order = vwTrainDetailExtend.SQLCOL_FULLNAME + " ASC";
        DataTable dtDetail = BLTrain.GetTrainDetailExtend(order);
        DataTable dtDetailOutput = dtDetail.Clone();
        dtDetailOutput.Clear();
        if (OrganizationHelper.IsUserInRole(CurrentUser.ID, AppConfig.MinistryAdminRoleID))
        {

            foreach (DataRow dr in dtDetail.Rows)
            {
                //按人事所在三级实体管理
                Department currMainDept = OrganizationHelper.GetDepartmentInfo(CurrentUser.MainDepartmentID);
                string deptPath = currMainDept.IDPath;
                string[] deptIDs = deptPath.Split('/');
                string mainDeptID = string.Empty;
                if (deptIDs.Length >= 4)
                {
                    mainDeptID = deptIDs[3];
                }
                else
                {
                    mainDeptID = CurrentUser.MainDepartmentID.ToString();
                }


                UserExtend userExtend = new UserExtend(new Guid(dr["ID"].ToString()));
                if (userExtend.Load())
                {
                    //取三级实体部门
                    Department dept = OrganizationHelper.GetDepartmentInfo(userExtend.MainDepartmentID);
                    if (dept != null)
                    {
                        string[] userDeptIDs = dept.IDPath.Split('/');
                        if (userDeptIDs.Length >= 4)
                        {
                            dr["ThirdLevelDeptDisplayName"] = OrganizationHelper.GetDepartmentInfo(new Guid(userDeptIDs[3])).DisplayName;
                        }
                    }
                }
                try
                {
                    dr["Birthday"] = Convert.ToDateTime(dr["Birthday"]).ToShortDateString();
                }
                catch (Exception)
                {
                }

                if (!string.IsNullOrEmpty(mainDeptID))
                {
                    if (OrganizationHelper.IsUserInDepartment(new Guid(dr["MemberID"].ToString()), new Guid(mainDeptID)))
                    {
                        dtDetailOutput.ImportRow(dr);
                    }
                }
            }
        }
        else if (OrganizationHelper.IsUserInRole(CurrentUser.ID, AppConfig.OrganizeAdminRoleID))
        {
            dtDetailOutput = BLTrain.GetTrainDetailExtend(order);
        }

        dtDetailOutput.Columns.Add("DeptDisplayName");
        dtDetailOutput.Columns.Add("BirthdayStr");
        dtDetailOutput.Columns.Add("TrainDayCount");
        dtDetailOutput.Columns.Add("TrainTime");
        foreach (DataRow dr in dtDetailOutput.Rows)
        {
            Wicresoft.Framework.Organization.User user = OrganizationHelper.GetUserInfo(new Guid(dr["ID"].ToString()));
            if (!string.IsNullOrEmpty(dr["Birthday"].ToString()))
            {
                dr["BirthdayStr"] = DateTime.Parse(dr["Birthday"].ToString()).ToString("yyyy-MM-dd");
            }
            if (!string.IsNullOrEmpty(dr["TrainClassID"].ToString()))
            {
                TrainClass trainClass = new TrainClass(new Guid(dr["TrainClassID"].ToString()));
                if (trainClass.Load())
                {
                    dr["TrainDayCount"] = trainClass.TrainDayCount;
                    dr["TrainTime"] = trainClass.BeginTime.ToString("yyyy-MM-dd") + "至" + trainClass.EndTime.ToString("yyyy-MM-dd");
                    dr["DeptDisplayName"] = trainClass.HostUnit;
                }
            }else
            if (!string.IsNullOrEmpty(dr["CreditID"].ToString()))
            {
                TrainCredit trainCredit = new TrainCredit(new Guid(dr["CreditID"].ToString()));
                if (trainCredit.Load())
                {
                    dr["TrainDayCount"] = trainCredit.TrainDayCount;
                    dr["TrainTime"] = trainCredit.BeginTime.ToString("yyyy-MM-dd") + "至" + trainCredit.EndTime.ToString("yyyy-MM-dd");
                    dr["DeptDisplayName"] = trainCredit.HostUnit;
                }
            }

        }

        for (int i = 0; i < dtDetailOutput.Rows.Count; i++)
        {
            DataRow dr = dtDetailOutput.Rows[i];
            string tableBodyItem = string.Format(tableBodyTemplate, dr["ThirdLevelDeptDisplayName"], dr["FullName"], dr["Gender"], dr["BirthdayStr"], dr["PositionLevel"], dr["Station"], dr["ClassName"],
                 dr["DeptDisplayName"], dr["TrainLevel"], dr["TrainDayCount"], dr["TrainTime"], dr["Score"], dr["PassTime"]);
            tableBody += tableBodyItem;
        }

        Response.Write(string.Format(tableBegin, "学习情况汇总表(" + DateTime.Now.ToString("yyyy-MM-dd") + ")") + tableBody + tableEnd);
        Response.End();
    }

    protected void rptUserInfo_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Label lFullName = e.Item.FindControl("lFullName") as Label;
            
            string id = DTUserPageList.Rows[e.Item.ItemIndex]["ID"].ToString();
            //NameControlLib.NameInfo userControl = new NameControlLib.NameInfo();
            //userControl.ID = "UserNameControl_" + id;
            //userControl.UserID = new Guid(id);
            //userControl.ScriptPath = "../Js/NameInfo.js";
            //lFullName.Controls.Add(userControl);
        }
    }



}
